﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace FourKillEnginePrototype
{
    public interface ISimpleSpriteSheet { Bitmap GetImage(double angle, int index);}

    public class SimpleSpriteSheet : ISimpleSpriteSheet
    {
        private Bitmap[][] _images = new Bitmap[4][];
        private int _tileWidth = 0, _tileHeight = 0;
        public SimpleSpriteSheet(Bitmap sheet, int tileWidth, int tileHeight)
        {
            _tileWidth = tileWidth;
            _tileHeight = tileHeight;

            for (int y = 0; y < sheet.Height / tileHeight; y++)
            {
                _images[y] = new Bitmap[4];
                for (int x = 0; x < sheet.Width / tileWidth; x++)
                {
                    _images[y][x] = CropImage(sheet, new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight));
                    //_images[y][x].Save(String.Format(@"c:\crops\{0}_{1}.png",x,y), ImageFormat.Png);
                }
            }
        }

        public Bitmap GetImage(double angle, int index)
        {

            var rad = Math.PI / 180;
            var a = angle > (Math.PI * 2) ? angle % (Math.PI * 2) : angle;

            if ((a >= 0 && a < Math.PI / 4) || (a >= 315 * rad && a <= Math.PI * 2)) // forward
                return _images[3][index];
            else if (a >= 45 * rad && a < 135 * rad) // left
                return _images[1][index];
            else if (a >= 135 * rad && a < 225 * rad)  // backward
                return _images[0][index];
            else // right
                return _images[2][index];
        }

        private static Bitmap CropImage(Bitmap img, Rectangle cropArea)
        {
            Bitmap bmpCrop = img.Clone(cropArea, img.PixelFormat);
            return bmpCrop;
        }
    }
}
